var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var token = require('../public/javascripts/utils');
var async = require('async');


function getTime() {
    return new Date().toLocaleString('chinese', {
        hour12: false,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    })
}

router.post('/', (req, res) => {
    var sql2 = "INSERT INTO `tasks` (img_id,user_id,owner_id,algorithm,status,start_time) VALUES (?,?,?,?,?,?)";
    var sql2Params = [req.body.image_id, token.verifyToken(req.headers.token), req.body.owner_id, 1, 0, getTime()];
    db.query(sql2, sql2Params, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log('insert into tasks', result);
            res.send({data: result.insertId})
        }
    })
})

router.delete('/', (req, res) => {
    console.log(req.body);
    var data = req.body;
    var sqls = {
        'sql1': "DELETE FROM images WHERE id = ?",
        'sql2': "DELETE FROM tasks WHERE img_id = ?",
        'sql3': "DELETE FROM users WHERE id = ?",
    }
    var tasks = ['sql1', 'sql2', 'sql3'];
    var id;
    async.eachSeries(tasks, function (item, callback) {
        if (item === 'sql1' || item === 'sql2') {
            id = data.image_id;
        } else {
            id = data.owner_id;
        }
        db.query(sqls[item], id, (err, result) => {
            if (err) {
                throw err;
                return
            } else {
                callback(err, result)
            }
        })
    }, function (err) {
        console.log(err);
        res.send('delete success')
    })
})

module.exports = router;